package com.moyu.common.security.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.moyu.common.core.constants.Constants;
import com.moyu.common.core.constants.HttpConstants;
import com.moyu.common.core.utils.JwtUtils;
import com.moyu.common.core.utils.ThreadLocalUtils;
import com.moyu.common.redis.service.RedisService;
import com.moyu.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @Author 赵彦博
 * @Date 2024/11/21 13:48
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

//    @Autowired
//    private TokenService tokenService;
//
//    @Autowired
//    private RedisService redisService;
//
//    @Value("${jwt.secret}")
//    private String secret;  //从哪个服务的配置文件中读取，取决于这个bean对象交给了哪个服务的spring容器进行管理。


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        String token = getToken(request);
//        if (token == null || "".equals(token)) return true;
//        // 从Redis中获取存储的token相关信息对应的Map
//        Map<String, Object> userTokenMap = redisService.getCacheObject(getUserIdFromToken(token), Map.class);
//        if (userTokenMap == null) {
//            log.error("未从Redis中找到对应token的用户信息");
//            return false;
//        }
//
//        // 从Map中获取userId
//        Long userId = (Long) userTokenMap.get("userId");
//
//        Claims claims = JwtUtils.parseToken(token, secret);
//
//        tokenService.extendSaTokenInRedis(userId);
        String loginIdAsString = StpUtil.getLoginIdAsString();
        ThreadLocalUtils.set(Constants.USER_ID, loginIdAsString);
        return true;
    }

//    private String getUserIdFromToken(String token) {
//        // 这里假设先解析JWT令牌获取其中的用户ID信息（如果token是JWT格式的话）
//        Claims claims = JwtUtils.parseToken(token, secret);
//        return claims.get("userId").toString();
//    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }

//    private String getToken(HttpServletRequest request) {
//        String token = request.getHeader(HttpConstants.AUTHENTICATION);
//        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
//            token = token.replaceFirst(HttpConstants.PREFIX, "");
//        }
//        return token;
//    }
}
